<template>
    <view style="padding: 10px;">
        <view class="uni-card">
			<view style="text-align: center;font-size: 18px;color: #f0ad4e;font-weight: 500;padding-bottom: 20px;">请选择导出条件</view>
			<view style="margin-bottom: 5px;">选择时间：</view>
			<view>
				<uni-datetime-picker v-model="rangeTime" type="datetimerange" :clearIcon="false"/>
			</view>
			<view style="margin-bottom: 5px;margin-top: 5px;">选择车间：</view>
            <uni-data-checkbox multiple mode="list" v-model="checkShop" :localdata="ShopOption"></uni-data-checkbox>
			<view>
				<button type="primary" class="uni-button-color"  @click="export1()">导出</button>
			</view>
        </view>
    </view>
</template>

<script>
import { timestampFormatDate } from '../../utils/FormatTime.js'
import { post, postForm } from '../../utils/request.js';
export default {
    data() {
        return {
			maskColor: 'rgba(0, 0, 0, 0.4)',
			userInfor: uni.getStorageSync('userInfor'),
			rangeTime: [Date.now() - 7*24*3600*1000, Date.now()],
			checkShop: [],
			ShopOption: [],
			isDerive : '',
			isRectify: '',
        }
    },
	
	onShow() {
		this.userInfor = uni.getStorageSync('userInfor')
		this.rangeTime = [Date.now() - 7*24*3600*1000, Date.now()]
		this.getAll()
	},
    onLoad() {
    },
    methods: {
	getAll() {
		let start = Date.now() - 7*24*3600*1000
		let end = Date.now()
		this.rangeTime = [timestampFormatDate(start, 'yyyy-MM-dd h:m:s'),timestampFormatDate(end, 'yyyy-MM-dd h:m:s')]
		//获取车间
			let shop = this.userInfor.workshopList
			let shopData = []
			for(var i = 0; i < shop.length; i++) {
				shopData[i] = {}
				shopData[i].value = shop[i].id
				shopData[i].text = shop[i].workshopName
			}
		this.ShopOption = shopData
	},
	dialogClose() {
		console.log('点击关闭')
	},
	
	export1() {
			// 显示加载提示
			     uni.showLoading({
			         title: '正在导出...',
			     });
				let checkShop = this.checkShop
				console.log(checkShop, 'checkShop')
			     // 发送 POST 请求
			     uni.request({
			         url: 'https://www.shagangtpm.cn/prod/problem/derive?worksopIds='+checkShop+ '&start=' + this.rangeTime[0]+ '&end=' + this.rangeTime[1], // 接口地址
			         method: 'POST', // 设置为 POST 请求
			         data: {
			             // 如果接口需要参数，在此添加，例如：
			             // param1: 'value1'
			         },
			         responseType: 'arraybuffer', // 处理二进制文件流
			         success: (res) => {
			             if (res.statusCode === 200) {
			                 // 从响应头中提取文件名
			                 const disposition = res.header['content-disposition'] || res.header['Content-Disposition'];
			                 let fileName = 'export'+ Date.now() +'.xlsx'; // 默认文件名
			                 if (disposition) {
			                     const matches = disposition.match(/filename=(.*)/);
			                     if (matches && matches[1]) {
			                         fileName = decodeURIComponent(matches[1]); // 解码文件名
			                     }
			                 }
			   
			                 // 保存文件到本地
			                 const fs = uni.getFileSystemManager();
			                 const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`;
			                 fs.writeFile({
			                     filePath: filePath,
			                     data: res.data,
			                     encoding: 'binary',
			                     success: () => {
			                         uni.hideLoading();
									 const sysInfo = wx.getSystemInfoSync()
									 if(sysInfo.platform.toLowerCase().indexOf('windows') >= 0) {
										 // 电脑PC端导出
										 wx.saveFileToDisk({
										 	filePath: filePath,
												success(e) {
													resolve({success:1,msg:'导出成功并打开',error:''})
										 		},
										 		fail(e) {  
										 			resolve({success:1,msg:'导出失败',error:e})
										 		}
										 })
									 } else {
										 // 可选：打开文件
										 uni.openDocument({
										     filePath: filePath,
										 	 showMenu: true,
										     fileType: 'xlsx',
										     fail: (err) => {
										         console.log('打开文档失败', err);
										 			uni.showToast({
										 				title: '打开文档失败',
										 				icon: 'fail',
										 			});
										     },
										 });
									 }
			                     },
			                     fail: (err) => {
			                         uni.hideLoading();
			                         uni.showToast({
			                             icon: 'none',
			                             title: '保存文件失败',
			                         });
			                         console.log('保存文件失败', err);
			                     },
			                 });
			             } else {
			                 uni.hideLoading();
			                 uni.showToast({
			                     icon: 'none',
			                     title: '导出失败，请重试',
			                 });
			             }
			         },
			         fail: (err) => {
			             uni.hideLoading();
			             uni.showToast({
			                 icon: 'none',
			                 title: '请求失败，请检查网络',
			             });
			             console.log('请求失败', err);
			         },
			     });
		},
	
   exportExcle() {
               // 显示加载提示
               uni.showLoading({
                   title: '正在导出...',
               });
			   let checkShop = this.checkShop
			   console.log(checkShop, 'checkShop')
               // 发送 POST 请求
               uni.request({
                   url: 'https://www.shagangtpm.cn/prod/problem/derive?worksopIds='+checkShop+ '&start=' + this.rangeTime[0]+ '&end=' + this.rangeTime[1], // 接口地址
                   method: 'POST', // 设置为 POST 请求
                   data: {
                       // 如果接口需要参数，在此添加，例如：
                       // param1: 'value1'
                   },
                   responseType: 'arraybuffer', // 处理二进制文件流
                   success: (res) => {
                       if (res.statusCode === 200) {
                           // 从响应头中提取文件名
                           const disposition = res.header['content-disposition'] || res.header['Content-Disposition'];
                           let fileName = 'export'+ Date.now() +'.xlsx'; // 默认文件名
                           if (disposition) {
                               const matches = disposition.match(/filename=(.*)/);
                               if (matches && matches[1]) {
                                   fileName = decodeURIComponent(matches[1]); // 解码文件名
                               }
                           }
   
                           // 保存文件到本地
                           const fs = uni.getFileSystemManager();
                           const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`;
                           fs.writeFile({
                               filePath: filePath,
                               data: res.data,
                               encoding: 'binary',
                               success: () => {
                                   uni.hideLoading();
								  //  uni.saveFile({
								  //       tempFilePath: filePath,
								  //       success: function (res) {
								  //       var savedFilePath = res.savedFilePath;
										// console.log(savedFilePath, '保存成功了')
								  //       }
								  //   });
          //                          uni.showToast({
          //                              title: '导出成功',
          //                              icon: 'success',
          //                          });
                                   // 可选：打开文件
                                   uni.openDocument({
                                       filePath: filePath,
									   showMenu: true,
                                       fileType: 'xlsx',
                                       fail: (err) => {
                                           console.log('打开文档失败', err);
											uni.showToast({
												title: '打开文档失败',
												icon: 'fail',
											});
                                       },
                                   });
                               },
                               fail: (err) => {
                                   uni.hideLoading();
                                   uni.showToast({
                                       icon: 'none',
                                       title: '保存文件失败',
                                   });
                                   console.log('保存文件失败', err);
                               },
                           });
                       } else {
                           uni.hideLoading();
                           uni.showToast({
                               icon: 'none',
                               title: '导出失败，请重试',
                           });
                       }
                   },
                   fail: (err) => {
                       uni.hideLoading();
                       uni.showToast({
                           icon: 'none',
                           title: '请求失败，请检查网络',
                       });
                       console.log('请求失败', err);
                   },
               });
           }
    }
}
</script>

<style>
    .uni-card {
        background-color: #fff;
        border-radius: 10px;
		padding: 20px;
    }
    .uni-button-color {
    	margin-top: 50px;
    	background-color: #007aff !important;
    }
</style>